<template>
  <div class="save-wrapper ui pc" >
    <div class="ui top attached tabular menu">
      <a class="item active" data-tab="first">基本信息</a>
    </div>
    <div class="ui bottom attached tab segment active" data-tab="first">
      <t-filed :data="filedOptions" @onchange="onchange" :nosubmit="true"></t-filed>
    </div>
    <div class="pc-actions">
      <button class="ui secondary button" @click="onsubmit">保 存</button>
      <button class="ui button" @click="oncancel">取 消</button>
    </div>
    <select-type @onsubmit="setType" @oncancel="oncancel" @onchange="changeType" :isEditType="isEditType" v-if="isActiveType" :active="isActiveType"></select-type>
  </div>
</template>
<script>
  import tool from 'src/util/tool';
  import util from '_util/index';
  import logic from '_logic';

  import selectType from './topProduct/selectType';
  import tFiled from 'components/tunit/tFields';


  export default {
      data() {
          return {
              query: {},
              typeData: null, //选择类型存储数据
              isActiveType: false,
              isEditType: false,
              params:{},
              inEdit:{},
              data:{},
              /* 基本表单 */
              filedOptions: [
                  {
                      label: "商品类型",
                      name: "type",
                      value:"--"
                  },{
                      label: "商品名称",
                      name: "name",
                      show_type: "input",
                      is_must: true,
                      value:"",
					  maxlength:30,
                  },{
                      label: "商品归属城市",
                      name: "city_code",
                      show_type:"city",
                      is_must: true,
                      citys:'',
                      "type": 12,
                      "city_type": 0,
                      "bind_type": 0,
                      "eidit_type": 4,
                      "data_type": 1,
                      "showType": 1,
                      // "value": "[{\"code\":\"110100\",\"title\":\"\\u5317\\u4eac\\u5e02\"}]",
                      value: ""
                  },{
                      label: "标签",
                      name: "tags",
                      show_type: "bind",
                      "bindModel": 46,
                      "data_type": 1,
                      "bind_type": 1,
                      "bind_name_field": "tag_names",
                      value: ""
                  },{
                      label: "商品图片(建议尺寸：750*442)",
                      name: "pic_url",
                      show_type: "upload",
                      pic_dir:1,
                      is_must: true,
                      value:""
                  },{
                      label: "特色推荐",
                      name: "introduction",
                      show_type: "textarea",
                      value:"",
                      placeholder:"请输入特色推荐",
                  },{
                      label: "商品描述",
                      name: "sdesc",
                      show_type: "editer",
                      is_must: true,
                      value:""
                  },{
                      label: "商品维护人员",
                      name: "maintain_uid",
                      show_type: "text",
                      value: ""
                  },{
                      label: "经纬度",
                      name: "latlon",
                      show_type: "latlon",
                      value:{
                          lng:"",
                          lat: ""
                      }
                  }
              ]
          }
      },
	  computed:{
		  current_page(){
			  return util.store.get(this,`current_page.TopProduct`,'list')||1
		  }
	  },
      components:{
          selectType,
          tFiled,
      },
      methods:{
          /*获取数据*/
          getData({url=[], data={}, callback=null, error=false, msg=null}){
              let param = {};
              for(let key of Object.keys( data ) ){
                  if(!/^\_.*$/.test(key)){
                      param[key] = data[key];
                  }
              }
              url = tool.getApi(this, url[0], url[1]);
              util.http.SR(this, url, param, msg, callback, {}, error);
          },
          /* 深度克隆 */
          deepClone(json){
              if(Array.isArray(json)){
                  return json.join("__##__").split("__##__");
              }
              let res = {};
              for(let key of Object.keys(json)){
                  res[key] = typeof( json[key] ) == "object" ? JSON.parse( JSON.stringify( json[key] ) ): json[key];
              }
              return res;
          },
          /*表单变化监控*/
          onchange(filed){
              let {name, value} = filed;
              if(~['off_address', 'pass_address', 'target_address'].indexOf(name)){
                  let resv = "";
                  ( typeof(value) == "object"? value : JSON.parse(value) ).forEach((item)=>{
                      resv += (resv?"|":"") + item.code;
                  });
                  value = resv;
              };
              if(~['city_code'].indexOf(name)){
                  value = JSON.parse(value)[0]
                  this.params = {...this.params,
                      city_code:value.code,
                      city_name:value.title,
                      province_code:value.prov,
                      province_name:value.prov_name
                  }
                  return
              }
              if(~['maintain_uid', 'tags'].indexOf(name)){
                  value = value.join("|");
              };
              if(name == "latlon"){
                  this.params.lng = value.lng;
                  this.params.lat = value.lat;
              };
              if(/^attr\_.*/.test(name)){
                  let {id, sort, attr_id} = filed.raw;
                  let newItem = {
                      attr_id: attr_id || id,
                      value:  typeof(value) != "object" ? value : (Array.isArray(value) && value.length == 0)? "":  JSON.stringify(value) ,
                      sort: sort
                  };
                  if(!this.params.attr){
                      this.params.attr = [];
                  }
                  let isExsist = false;
                  this.params.attr.map((item)=>{
                      if(isExsist){
                          return item
                      }
                      if(item.sort == sort){
                          isExsist = true;
                          Object.assign(item, newItem);
                      }
                      return item;
                  });
                  if(!isExsist){
                      this.params.attr.push(newItem);
                  };
                  return;
              }
              this.params[name] = value;
          },

          /* 改变商品类型 */
          changeType({data, show}){
              for(let ind of Object.keys(data)){
                  let key = ind, val = data[ind];
                  if(ind == "type_id"){
                      key = "type";
                      this.filedOptions.forEach((item) => {
                          if(item.name == key){
                              item.value = show[ ind ].text;
                          }
                          // Todo...
                      })
                  };
                  if(!val){
                      delete this.params[ key ];
                  }else{
                      this.params[ key ] = val;
                      this.inEdit[ key ] = val;
                  }
              }
          },
          /* 设置商品类型 */
          setType({data, show}){
              this.changeType({data, show});
              this.typeData = {data, show};
              this.isActiveType = false;
              this.getTypeAttr( this.params.type || data.type_id );
              // this.setBaseData();
          },
          /*获取自定义字段*/
          getTypeAttr(typeId){
              let _this = this;
              this.getData({
                  url:['ProductType','getTypeAttr'],
                  data: {type_id: typeId},
                  callback(rs){
                      if(rs[1]){
                          _this.setAttrOption(rs[1], true);
                      }
                  }
              })
          },
          /* 初始化 city */
          setAttrCity(){
              let _this = this
              this.filedOptions[2].citys = JSON.stringify([{
                  code:_this.params.city_code,
                  prov:_this.params.province_code,
                  prov_name:_this.params.province_name,
                  title:_this.params.city_name
              }])
          },
          /* 初始化 自定义字段 */
          setAttrOption(rs = [], isNew=false){
              let _this = this;
              rs.sort((a, b)=>{
                  return a.sort * 1> b.sort * 1;
              });
              if(!this.inEdit.attr){
                  this.inEdit.attr = [];
              }
              let normal = []
              let speciel = rs.filter((item, index)=>{
                  if(item.need_api != 1){
                      let {title, attr_name, show_type, value, sort, attr_id, values=""} = rs[index];
                      let res = Object.assign(item, {
                          label: title || attr_name,
                          name: "attr_"+sort,
                          show_type_code: show_type,
                          value: isNew ? "" : value,
                          element: isNew ? value : values
                      });
                      res._raw = _this.deepClone( item );
                      normal.push(res);
                  }
                  return item.need_api == 1;
              });
              if(speciel.length>0){
                  this.getData({
                      url:['Bindconf', 'getBindConf'],
                      data:{bindModel: speciel.map(({value}) => {
                          return (value||[])[0]
                      }).join("|")},
                      callback(_rs){
                          _rs.map((item, index)=>{
                              let {title, show_type, value, sort, attr_name} = rs[index];
                              let res = Object.assign(item, speciel[index], {
                                  label: title || attr_name,
                                  name: "attr_"+sort,
                                  show_type_code: show_type,
                                  value: value,
                              });
                              res._raw = _this.deepClone( res );
                              return res;
                          });
                          _this.DoSetAttrOption(normal.concat( _rs ))
                      }
                  });
                  return;
              }
              _this.DoSetAttrOption(rs);
              _this.setAttrCity();
          },
          DoSetAttrOption(fields){
              if(!this.params.attr){
                  this.params.attr = []
              }
              fields.sort((fielda, fieldb)=>{
                  return fielda.sort > fieldb.sort;
              });
              fields.forEach((item) => {
                  let {title, show_type, value="", id, sort, attr_id} = item;
                  item.value = value;
                  let isExsist = false;

                  this.params.attr.forEach((_item) => {
                      if(!isExsist){
                          isExsist = attr_id == _item.attr_id;
                      }
                  });
                  this.filedOptions.push(item);
                  if(!isExsist){
                      this.params.attr.push({attr_id: attr_id || id, sort:sort, value });
                      return;
                  }
              });
          },
          /* 编辑数据 */
          editProduct(){
              this.params = this.deepClone( this.inEdit );
              if(!this.params.navigation_id){
                  this.isActiveType = true;
                  this.isEditType = true;
              }
              this.setAttrOption( this.inEdit.attr );
              this.setBaseData();
          },
          /* 新增数据 */
          newProduct(){
              this.isActiveType = true;
              this.setBaseData();
          },
          /* 处理 或 更新基本数据 */
          setBaseData(){
              let _this = this;
              this.filedOptions.forEach((item, index) => {
                  if(item.name == "type"){
                      if(_this.typeData){
                          item.value = this.params.type_name || _this.typeData.show["type_id"].text;
                      }
                      if(this.params.type_name){
                          item.value = this.params.type_name
                      }
                      return;
                  }
                  if(item.name == "latlon"){
                      item.value.lng = this.params.lng;
                      item.value.lat = this.params.lat;
                      return;
                  };
                  if(item.name == "maintain_uid"){
                      if(!this.params.maintain_name){
                          this.filedOptions[index] = {
                              label: "商品维护人员",
                              name: "maintain_uid",
                              show_type: "bind",
                              is_must: true,
                              "bindModel": 86,
                              "data_type": 0,
                              "bind_type": 1,
                              "need_get_bind_name": 1,
                              "bind_name_field": "name",
                              value: ""
                          };
                          return;
                      }
                      this.filedOptions[index].value = this.params.maintain_name;
                      return;
                  }
                  if( this.params [ item.name + "_name"] ){
                      item.value = this.params[ item.name + "_name" ];
                  }else if( this.params[ item.name ] ){
                      item.value = this.params[ item.name ];
                  };
              });
          },
          /* 取消提交 */
          oncancel(){
			   this.$router.push({path:'/page/list', query: {ctl: "TopProduct",to_p:`${this.current_page}`}});
          },
          isVerify(cb=()=>{}){
              let isOk = true;
              let _this = this;
              let verifyFiled = this.filedOptions.filter((item)=>{
                  return item.is_must == true
              });
              verifyFiled.forEach(({is_must, label, name, id, attr_id}) => {
                  let value = "";
                  // 是否有不符合规则的数据
                  if(!isOk){
                      return;
                  }
                  if(/^attr\_.*$/.test(name)){
                      value = ( (this.params.attr||[]).filter(item=>{
                          return item.attr_id == id || item.attr_id == attr_id;
                      })[0] ||{} ).value;
                  }else{
                      value = _this.params[name];
                  }
                  if(!value){
                      util.showMsg(_this,'warning', `请补充 [${label}] 信息`);
                      isOk = false;
                  }
              });
              if(!isOk){return}
              cb(this.params);
          },
          /* 提交修改 */
          onsubmit(){
              let _this = this;
              let url = this.inEdit.id ? 'update' : 'insert';
              let msg = this.inEdit.id ? '商品更新成功' : '商品添加成功';
              this.isVerify(params=>{
                  this.getData({
                      url: ['TopProduct', url],
                      data: params,
                      callback(res){
                          _this.$router.push({path:'/page/list', query: {ctl: "TopProduct",to_p:`${_this.current_page}`}});
                          util.showMsg(_this,'success', msg);
                      }
                  });
              })
          },
      },
      watch:{
          "$route.query": function(val){
              // this.updateView(val);
          },
      },
      created() {
		  document.querySelectorAll('.header-wrapper')[0].style.zIndex = 11
          this.query = this.$route.query;
          this.inEdit = this.deepClone( this.$store.state.global.editVo );
          if(this.inEdit.id){
              /* 编辑商品模式 */
              this.editProduct();
          }else{
              /* 新商品模式 */
              this.newProduct();
          }
      }
  }
</script>
<style rel="stylesheet/less" scoped lang="less">;
   .pc{
    padding-bottom: 60px;
    &-actions{
      position: fixed;
      left: 210px;
      right: 20px;
      bottom: 10px;
      padding-top: 10px;
      z-index: 5;
      background: linear-gradient(to top, rgba(255,255,255, 1) 0%, rgba(255,255,255,0) 100%);
    }
    &-block{
      &-title{
        font-size: 14px;
        height: 26px;
        line-height: 26px;
        margin-bottom: 10px;
      }
    }
  }
</style>
